package com.du.spring.dao.impl;

import com.du.spring.pojo.User;
import com.du.spring.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;

/**
 * @author : DuJiabao
 * @Date : 2021/2/5 10:29
 * @Project : spring
 * @File : null.java
 * @Desc :
 */
// 一般用于持久层（DAO）
@Repository
public class UserDaoImpl implements UserDao {
  @Autowired
  JdbcTemplate jdbcTemplate;

  @Override
  public int addUser(User user) {
    String sql = "insert into user_info(username, phone) values(?,?);";
    return jdbcTemplate.update(sql, user.getUsername(), user.getPhone());
  }

  @Override
  public int countUser() {
    String sql = "select count(*) from user_info";
    Integer res = jdbcTemplate.queryForObject(sql, Integer.class);
    if (res != null) return res;
    throw new RuntimeException("查不到");
  }

  @Override
  public User selectUserById(int id) {
    String sql = "select * from user_info where id = ?";
    User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
    if (user != null) return user;
    throw new RuntimeException("查不到");
  }

  @Override
  public List<User> selectUsers() {
    String sql = "select id, username, phone from user_info";
    // RowMapper 是接口，针对返回不同类型数据，使用这个接口里面实现类完成数据封装
    return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
  }

  @Override
  public int deleteUserById(int id) {
    String sql = "delete from user_info where id = ?";
    return jdbcTemplate.update(sql, id);
  }

  @Override
  public int updateUser(User user) {
    String sql = "update user_info set username = ?, phone = ? where id = ?;";
    return jdbcTemplate.update(sql, user.getUsername(), user.getPhone(), user.getId());
  }

  @Override
  public void batchAddUsers(List<Object[]> batchArgs) {
    String sql = "insert into user_info(username, phone) values(?,?);";
    // 批量执行sql,并传入多个数组组成的参数
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(ints));
  }

  @Override
  public void batchUpdateUsers(List<Object[]> batchArgs) {
    String sql = "update user_info set username = ?, phone = ? where id = ?;";
    // 批量执行sql,并传入多个数组组成的参数
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(ints));
  }

  @Override
  public void batchDeleteUsers(List<Object[]> batchArgs) {
    String sql = "delete from user_info where id = ?";
    // 批量执行sql,并传入多个数组组成的参数
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(ints));
  }
}
